package com.yangjie.autotest.hpsa.component;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import com.yangjie.autotest.context.ContextIF;
import com.yangjie.autotest.context.GlobalContextProperty;
import com.yangjie.autotest.testcase.xml.Params;
import com.yangjie.autotest.testcase.xml.TestCases;
import com.yangjie.autotest.testcase.xml.Variable;
import com.yangjie.autotest.util.StringUtils;
import com.yangjie.autotest.util.TestCaseUtils;
import com.yangjie.log.LoggerIF;

@Named("ftpComp")
public class FTPComponent {

	@Inject
	private LoggerIF logger = null;

	
	private String ip = null;

	
	private String port = null;
	
	
	private String username = null;
	
	private String password = null;
	
//	private String targetDir = null;
	private String targetRootDir = "";

	
	public Boolean init(String ip, String port, String username, String password) {
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
		return true;
	}
	
	public Boolean init(String ip, String port, String username, String password, String targetRootDir) {
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.password = password;
		this.targetRootDir = targetRootDir;
		if(this.targetRootDir == null) {
			this.targetRootDir = "";
		}
		return true;
	}

	private void uploadFile2(FTPClient client, String targetFileName, String filename, InputStream is) throws Exception{
		try {
			client.storeFile(targetFileName, is);
			logger.debug("result of uploading file " + filename + " to " + targetFileName + " is " + client.getReplyString());

			is.close();
			int reply = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				throw new Exception("upload file " + filename + " to " + targetFileName + " failed");
			} else {
				return;
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

	}

	public void uploadFile(ContextIF context, Params params) throws Exception{
		String baseFileName = TestCaseUtils.getParamValue(params, "file");
		String suffix = TestCaseUtils.getParamValue(params, "suffix");
		if(StringUtils.isEmptyString(suffix)) {
			suffix = "false";
		}
		String outputFileNameVar = TestCaseUtils.getParamValue(params, "outputFileNameVar");
		if(StringUtils.isEmptyString(outputFileNameVar)) {
			outputFileNameVar = "ftpFileName";
		}
		String uploadEOFFile = TestCaseUtils.getParamValue(params, "uploadEOFFile");
		if(StringUtils.isEmptyString(uploadEOFFile)) {
			uploadEOFFile = "false";
		}
		String targetDir = TestCaseUtils.getParamValue(params, "targetDir");
		String content = TestCaseUtils.getParamValue(params, "content");
		if(StringUtils.isEmptyString(content)) {
			uploadFile(context, outputFileNameVar, baseFileName, suffix, uploadEOFFile, targetDir);
		} else {
			uploadFile(context, outputFileNameVar, baseFileName, suffix, uploadEOFFile, targetDir, content);
		}
	}
	
//	private void uploadFile(String fileArg, String targetDir) throws Exception{
//		uploadFile(fileArg, "false", "false", targetDir);
//	}
	private void uploadFile(ContextIF context, String outputFileNameVar, String fileArg, String suffix, String uploadEOFFile, String targetDir, String content) throws Exception {
		File file = new File(fileArg);
		OutputStream os = new FileOutputStream(file);
		os.write(content.getBytes());
		os.close();
		uploadFile(context, outputFileNameVar, fileArg, suffix, uploadEOFFile, targetDir);
	}
	
	
	private void uploadFile(ContextIF context, String outputFileNameVar, String fileArg, String suffix, String uploadEOFFile, String targetDir) throws Exception {
		targetDir = targetRootDir + targetDir;
//		String addRadomSuffix = (String) paramMap.get("addRadomSuffix");
//		String uploadEOFFile = (String) paramMap.get("uploadEOFFile");
		String[] fileArray = fileArg.split(",");
		List<String> fileList = new LinkedList<String>();
		for (int i = 0;i<fileArray.length; i++) {
			String file = (String) fileArray[i];
			
		
			fileList.add(file);
		}

		FTPClient client = new FTPClient();
		boolean result = true;
		try {
			client.connect(ip, Integer.parseInt(port));

			int reply = client.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				client.disconnect();
				logger.debug("connect to FTP server failed.");
				throw new Exception("connect to FTP server failed.");
			}

			client.login(username, password);
			client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
			client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);

			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String date = sdf.format(Calendar.getInstance().getTime());
			
			for (int i = 0; i < fileList.size(); i++) {
				String filePath = fileList.get(i);
				File file = new File(filePath);
				String filename = file.getName();
//				String filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1);

				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));

				String targetFileName = filename + "_" + date + "_" + Math.random();
				if ("NONE".equalsIgnoreCase(suffix)) {
					targetFileName = filename;
				} else if(suffix.toLowerCase().contains("date")) {
					targetFileName = addDateSuffix(suffix, filename);
				}
				
				Variable ftpNameVariable = new Variable();
				ftpNameVariable.setName(outputFileNameVar);
				ftpNameVariable.setValue(targetFileName);
				
				targetFileName = targetDir + File.separator + targetFileName;
				
	
				((TestCases)context.getProperty(GlobalContextProperty.TESTCASES)).getVariables().getVariable().add(ftpNameVariable);
				uploadFile2(client, targetFileName, filename, bis);
				
				if ("true".equalsIgnoreCase(uploadEOFFile)) {
					targetFileName = targetFileName + ".EOF";
					bis = new BufferedInputStream(new ByteArrayInputStream(new byte[0]));
					uploadFile2(client, targetFileName, filename, bis);
				}
			}
			


			client.logout();

			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	public String addDateSuffix(String suffix, String fileName) {
//		int index = suffix.toLowerCase().indexOf("date_");
		String dateFormat = suffix.replace("date_", "");
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		String dateSuffix = sdf.format(Calendar.getInstance().getTime());
		
		return fileName + "." + dateSuffix;
	}
	
	
	public static void main(String[] args) {
		
	}

}
